import re
import time
import requests
import uuid
import datetime
from flask import make_response, request, send_from_directory
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial
import json
import logging
from flask_mail import Message

from redash import models, limiter, mail, settings
from redash.permissions import (
    require_default,
    require_admin,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)
from redash.settings import parse_boolean
from redash import settings

import sys
import random
from typing import List


class QueryShowFieldNewResource(BaseResource):

    @require_default
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))
        queryshowfield_id=req["id"]
        queryshowfield = models.QueryShowField(
        id=queryshowfield_id,
        org=self.current_org,
        code = req["code"],
        name = req["name"],
        fieldsshow = req["fieldsshow"],
        fieldsall = req["fieldsall"],
        message = req["message"],       
        userid = req["userid"],
        )
        try:
            models.db.session.add(queryshowfield)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)


class QueryShowFieldResource(BaseResource):
    def get(self, queryshowfield_id):
        result = models.QueryShowField.get_by_id(queryshowfield_id)
        return result.to_dict()

    @require_default
    def post(self, queryshowfield_id):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))

        queryshowfield = models.QueryShowField.get_by_id(queryshowfield_id)
        params = dict(fieldsshow = req["fieldsshow"],fieldsall = req["fieldsall"],
            message = req["message"], userid = req["userid"])
        try:
            self.update_model(queryshowfield, params)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

class QueryShowFieldDeleteResource(BaseResource):
    @require_default
    def post(self, queryshowfield_id):
        queryshowfield =  models.QueryShowField.get_by_id(queryshowfield_id)
        models.db.session.delete(queryshowfield)
        models.db.session.commit()

class QueryShowFieldCodeResource(BaseResource):
    def get(self, queryshowfield_code):
        result = models.QueryShowField.get_by_code(queryshowfield_code)
        return result.to_dict()

class QueryShowFieldListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        code = req["code"] if "code" in req else ""
        name = req["name"] if "name" in req else ""
        userid = str(req["userid"]) if "userid" in req else ""

        orderfield = req["orderfield"] if "orderfield" in req else "code"
        order = req["order"] if "order" in req else 0
        if orderfield=="code" :
            orderfield ="t1.code"
        elif orderfield=="name":
            orderfield ="t1.name"
        else:
            orderfield ="t1.code"        

        strwhere ="t1.org_id=" +str(self.current_org.id)
        if code !="" :
            strwhere = strwhere + " and t1.code like '%"+code+"%'"
        if name !='' :
            strwhere = strwhere + " and t1.name like '%"+name+"%'"

        strgetfield =""" t1.*"""
        tblname = """public.queryshowfield t1 """

        result = models.Enums.get_pagequery(tblname,strgetfield,orderfield,page_size,page,order,strwhere)
        return result[0]


